package blazingbubble.network.game;

import spark.network.Sender;
import spark.network.ServerConnection;
import spark.network.NetworkConnection;
import spark.network.IPreLoginResponseResultListener;
import blazingbubble.network.game.GameDemon;
import blazingbubble.network.game.GameStrategyFactory;
import blazingbubble.exception.StartupException;

import java.net.SocketException;
import java.net.InetAddress;

import org.apache.log4j.Logger;

public class NetGame {
	private static Logger logger = Logger.getLogger(NetGame.class);

	private Sender sender;
	private GameDemon demon;
	private ServerConnection serverConnection;

	public void startup(InetAddress gameAddress, int gamePort, GameStrategyFactory strategyFactory) throws StartupException {
		logger.info("Starting up game ...");
		try {
			serverConnection = new ServerConnection(gameAddress, gamePort);
			sender = new Sender();
			demon = new GameDemon(serverConnection, sender, strategyFactory);
			new Thread(demon).start();
		}
		catch(SocketException e) {
			throw new StartupException(e);
		}

		logger.info("Game startup complete.");
	}

	public int getQueryPort() {
		return demon.getSocketPort();
	}

	public Sender getSender() {
		return sender;
	}

	public NetworkConnection getServerConnection() {
		return serverConnection.getServerConnection();
	}

	public void setPreLoginResponseListener(IPreLoginResponseResultListener preLoginResponseListener) {
		demon.setPreLoginResponseListener(preLoginResponseListener);
	}

	public void shutdown() {
		logger.info("Shutting down NetGame ...");
		if(demon != null) {
			demon.shutdown();
		}
		logger.info("NetGame shutdown complete.");
	}
}